package com.albatross.rest;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.persistence.Column;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import beans.VulnerabilityMaster;

public class VulnerabilityDataSource {

	public String callURL(String myURL) {
		System.out.println("Requeted URL:" + myURL);
		StringBuilder sb = new StringBuilder();
		URLConnection urlConn = null;
		InputStreamReader in = null;
		try {
			URL url = new URL(myURL);
			urlConn = url.openConnection();
			if (urlConn != null)
				urlConn.setReadTimeout(60 * 10000);
			if (urlConn != null && urlConn.getInputStream() != null) {
				in = new InputStreamReader(urlConn.getInputStream(),
						Charset.defaultCharset());
				BufferedReader bufferedReader = new BufferedReader(in);
				if (bufferedReader != null) {
					int cp;
					while ((cp = bufferedReader.read()) != -1) {
						sb.append((char) cp);
					}
					bufferedReader.close();
				}
			}
			in.close();

		} catch (Exception e) {
			throw new RuntimeException("Exception while calling URL:" + myURL,
					e);
		}

		// System.out.println("\nOutput: \n" + sb.toString());

		return sb.toString();

	}

	public String callFile(String myFile) {
		System.out.println("Requested File:" + myFile);
		StringBuilder stringJson = new StringBuilder();

		try {


		FileReader logReader = new FileReader(myFile);
		BufferedReader buffer = new BufferedReader(logReader);
		if (buffer != null) {
		int cp;
		while ((cp = buffer.read()) != -1) {
		stringJson.append((char) cp);
		}
		buffer.close();
		} }



		 catch (Exception e) {
		throw new RuntimeException("Exception while reading File:" + myFile,
		e);
		 }



		return stringJson.toString();

		}
	
	
	public List<VulnerabilityMaster> getVulEntity(String sb) {
		// TODO Auto-generated method stub

		List<VulnerabilityMaster> li = new ArrayList<VulnerabilityMaster>();

		JSONParser parser = new JSONParser();
		String id = null;
		String ip = null, protocol = null;
		Long Host_Port;
		Boolean failOnEmpty = null;
		int patchable, pci_flag, qid, qualisTickets, daysToLive = 0;

		Long createdAtMS = null, hash = null;

		Timestamp created_at_timestamp = null;
		String crawlId = null, createdAt, firstseen = null;
		Boolean isNew = null;
		String name = null;

		Boolean isHashChanged = null;
		Long timeseen = null;
		String firstseen_timestamp = null;
		java.sql.Timestamp firstseen_TimeStamp = null;
		java.sql.Timestamp firstseen1_TimeStamp = null;
		java.sql.Timestamp last_Fixed_Date_timestamp = null;
		java.sql.Timestamp last_Found_Date_timestamp = null;
		java.sql.Timestamp last_service_modification_datetime_timestamp = null;
		java.sql.Timestamp last_test_datetime_timestamp =null;
		java.sql.Timestamp last_update_datetime_timestamp=null;
		try {
			VulnerabilityMaster v;
			Object obj = parser.parse(sb.toString());
			JSONObject mainArray = (JSONObject) obj;
			JSONArray jsonMainArr = (JSONArray) mainArray.get("results");

			String jsonMainArr1 = (String) mainArray.get("next");

			System.out.println("total size" + jsonMainArr.size());
			for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**

				JSONObject childJSONObject = (JSONObject) jsonMainArr.get(i);
				id = (String) childJSONObject.get("id");
				ip = (String) childJSONObject.get("ip");
				Host_Port = (Long) childJSONObject.get("port");
				String last_Fixed_Date = (java.lang.String) childJSONObject
						.get("last_fixed_datetime");
				SimpleDateFormat format1 = new SimpleDateFormat(
						"yyyy-MM-dd'T'HH:mm:ss.sss'Z'");

				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd'T'HH:mm:ss'Z'");
				if (last_Fixed_Date != null) {
					last_Fixed_Date_timestamp = new Timestamp(format.parse(
							last_Fixed_Date).getTime());
				} else {
					last_Fixed_Date_timestamp = null;
				}
				String last_Found_Date = (java.lang.String) childJSONObject
						.get("last_found_datetime");

				String last_service_modification_datetime = (java.lang.String) childJSONObject
						.get("last_service_modification_datetime");

				String last_test_datetime = (java.lang.String) childJSONObject
						.get("last_test_datetime");
				String last_update_datetime = (java.lang.String) childJSONObject
						.get("last_update_datetime");

				patchable = Integer.parseInt((String) childJSONObject
						.get("patchable"));

				pci_flag = Integer.parseInt((String) childJSONObject
						.get("pci_flag"));

				protocol = (java.lang.String) childJSONObject.get("protocol");

				String published_datetime = (java.lang.String) childJSONObject
						.get("published_datetime");
				java.sql.Timestamp published_datetime_timestamp = new Timestamp(
						format.parse(published_datetime).getTime());

				if (last_Found_Date != null) {
					last_Found_Date_timestamp = new Timestamp(format.parse(
							last_Found_Date).getTime());
				} else {
					last_Found_Date_timestamp = null;
				}

				if (last_service_modification_datetime != null) {
					last_service_modification_datetime_timestamp = new Timestamp(
							format.parse(last_service_modification_datetime)
									.getTime());
				} else {
					last_service_modification_datetime_timestamp = null;

				}

				
				if (last_test_datetime != null) {
					last_test_datetime_timestamp = new Timestamp(
							format.parse(last_test_datetime)
									.getTime());
				} else {
					last_test_datetime_timestamp = null;

				}
				if (last_update_datetime != null) {
					last_update_datetime_timestamp = new Timestamp(
							format.parse(last_update_datetime)
									.getTime());
				} else {
					last_update_datetime_timestamp = null;

				}

				
				
				qid = Integer.parseInt((String) childJSONObject.get("qid"));
				int[] qts = null;
				if (childJSONObject.get("qualys_tickets") == null) {
					qts = null;
				} else {

					qts = null;
				}

				String qualisType = (java.lang.String) childJSONObject
						.get("qualys_type");

				String severity_level = (java.lang.String) childJSONObject
						.get("severity_level");

				JSONObject jsonSubArrayJSONObject = (JSONObject) parser
						.parse(childJSONObject.get("source").toString());
				// JSONArray jsonSubArray=(JSONArray) obj1.get("source");

				// System.out.println("json source1 is" +
				// jsonSubArrayJSONObject);
				// System.out.println("json source is"
				// + jsonSubArrayJSONObject.get("crawl_id"));

				crawlId = (java.lang.String) jsonSubArrayJSONObject
						.get("crawl_id");
				createdAt = (java.lang.String) jsonSubArrayJSONObject
						.get("created_at");
				if (createdAt == null) {
					created_at_timestamp = null;
				} else {
					/*
					 * java.sql.Timestamp a = new Timestamp(
					 * format.parse(createdAt).getTime()); created_at_timestamp
					 * = a;
					 */
					created_at_timestamp = null;

				}
				if (jsonSubArrayJSONObject.get("created_at_ms") == null) {
					createdAtMS = null;
				} else {
					// createdAtMS =(Long)
					// jsonSubArrayJSONObjec.get("created_at_ms");
					createdAtMS = null;
				}
				if (jsonSubArrayJSONObject.get("days_to_live") != null) {
					daysToLive = Integer
							.parseInt((String) jsonSubArrayJSONObject

							.get("days_to_live"));
				} else {
					daysToLive = 0;
				}
				if (jsonSubArrayJSONObject.get("fail_on_empty") != null) {
					failOnEmpty = (Boolean) jsonSubArrayJSONObject
							.get("fail_on_empty");
				} else {
					failOnEmpty = null;
				}

				String firstseen1 = (java.lang.String) jsonSubArrayJSONObject
						.get("firstSeen");
				if (firstseen1 != null) {

					firstseen1_TimeStamp = new Timestamp(format1.parse(
							firstseen1).getTime());

				}

				else {
					firstseen_timestamp = null;

				}
				if (jsonSubArrayJSONObject.get("hash") != null)
					hash = (Long) jsonSubArrayJSONObject.get("hash");
				else {
					hash = null;
				}

				if (jsonSubArrayJSONObject.get("isHashChanged") != null) {

					isHashChanged = (Boolean) (jsonSubArrayJSONObject
							.get("isHashChanged"));
				} else {
					isHashChanged = null;
				}
				if (jsonSubArrayJSONObject.get("isNew") != null) {
					isNew = (Boolean) jsonSubArrayJSONObject.get("isNew");
				}

				else {
					isNew = null;
				}
				if (jsonSubArrayJSONObject.get("name") != null) {
					name = (java.lang.String) jsonSubArrayJSONObject
							.get("name");
				} else {
					name = null;
				}
				if (jsonSubArrayJSONObject.get("timesSeen") != null) {
					timeseen = (Long) jsonSubArrayJSONObject.get("timesSeen");
				} else {
					timeseen = null;
				}

				char[] status = null;
				if (childJSONObject.get("status") != null) {
					status = ((String) childJSONObject.get("status"))
							.toCharArray();

				} else {
					status = null;
				}
				String ticketNumber = (java.lang.String) childJSONObject
						.get("ticketNumber");
				String title = (java.lang.String) childJSONObject.get("title");
				String type = (java.lang.String) childJSONObject.get("type");

				String vuln_type = (java.lang.String) childJSONObject
						.get("vuln_type");

				// Parameters start with 1
				v = new VulnerabilityMaster();
				v.setAppId(id);
				v.setAppIp(ip);
				v.setHostPort((int) Host_Port.longValue());
				v.setLastFixedDateTime(last_Fixed_Date_timestamp);
				v.setLastFoundDateTime(last_Found_Date_timestamp);
				v.setLastServiceModDateTime(last_service_modification_datetime_timestamp);
				v.setLastTestDateTime(last_test_datetime_timestamp);
				v.setLastUpdateDateTime(last_update_datetime_timestamp);
				v.setPatchable(patchable);
				v.setPciFlag(pci_flag);
				v.setProtocol(protocol);
				v.setPublishedDateTime(published_datetime_timestamp);
				v.setQualisId(qid);
				v.setQualisTickets(qts);
				v.setQualisType(qualisType);
				v.setSeverityLevel(severity_level);

				v.setCrawlId(crawlId);
				// v.setCreatedAt(created_at_timestamp);
				v.setCreatedAtMS(createdAtMS);
				v.setDaysToLive(daysToLive);
				v.setFailOnEmpty(failOnEmpty);
				v.setFirstseen(firstseen1_TimeStamp);

				v.setHash(hash);
				v.setIsHashChanged(isHashChanged);
				v.setIsNew(isNew);
				v.setName(name);
				v.setTimeseen(timeseen);

				v.setStatus(status);
				v.setTicketNumber(ticketNumber);
				v.setTitle(title);
				v.setType(type);
				v.setVulnerabilityType(vuln_type);

				li.add(v);

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return li;
	}
}
